<?php

namespace App\Admin\Models;

use App\Admin\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\MessageBag;
use Ixudra\Curl\Facades\Curl;
use Encore\Admin\Facades\Admin;
use DB;

class Activity extends BaseModel
{   
    //指定主键
    protected $primaryKey = 'adId';
    
    protected $table = 'activity_definition';
    
    // 获取有效分享数
    public function getShareNumPerson($adId){
    	
    	$shareNumPerson = DB::table('activity_share_view')->where('adId', $adId)->count();
    	return $shareNumPerson;
    }
    
    // 获取分享返佣金额
    public function getShareMoneyInfo($adId){
    	
    	$shareMoneyInfo = DB::table('activity_apply')
    						->selectRaw('SUM(aaShareMoney) AS totalShareMoney, SUM(aaShareMoney) * 0.006 AS commission ')
    						->where('adId', $adId)
    						->where('aaStats', 1)
    						->where('aaId', '>', 123)
    						->first();
    	return $shareMoneyInfo;
    }
    
    // 获取参与返佣人数
    public function getHaveMoneyNum($adId){
    	
    	$num = DB::table('activity_apply')
						->where('adId', $adId)
						->where('aaStats', 1)
						->where('aaShareMoney', '>', 0)
						->count();
		return $num;
    }
    
	// 每日数据统计
    public function getDayStats($adId){
    	
    	$adInfo = DB::table('activity_definition')->where('adId', $adId)->first();
    	
    	$sqlDayStats = "SELECT sd.`day`, IFNULL(t.dayApplyNum,0) AS dayApplyNum, IFNULL(t.dayShareMoney,0) AS dayShareMoney, IFNULL(t2.dayDisNum,0) AS dayDisNum, IFNULL(t2.dayDisMoney,0) AS dayDisMoney
FROM sys_day AS sd
LEFT JOIN 
(
SELECT DATE_FORMAT(aa.createTime, '%Y-%m-%d') AS aaDay, COUNT(1) AS dayApplyNum, SUM(aa.aaShareMoney) AS dayShareMoney
FROM activity_apply AS aa
WHERE aa.adId = ? AND aa.aaStats = 1
GROUP BY DATE_FORMAT(aa.createTime, '%Y-%m-%d')
) AS t ON sd.`day` = t.aaDay
LEFT JOIN
(
SELECT DATE_FORMAT(db.createTime, '%Y-%m-%d') AS dbDay, COUNT(1) AS dayDisNum, SUM(db.dbSaleMoney)-SUM(db.dbSurplusMoney) AS dayDisMoney
FROM distribution_bill AS db
WHERE db.dcId = ? AND db.createTime >= ? AND db.createTime < ? AND db.createTime < NOW() AND db.dbMemo = ?
GROUP BY DATE_FORMAT(db.createTime, '%Y-%m-%d') 
) AS t2 ON sd.`day` = t2.dbDay
WHERE sd.`day` >= ? AND sd.`day` < ? AND sd.`day` < NOW()
ORDER BY sd.`day` DESC;";
		
		$infoList = DB::select($sqlDayStats, [$adId, $adInfo->acId, $adInfo->adApplyBeginTime, $adInfo->adApplyEndTime, 
												'activity_'.$adId, $adInfo->adApplyBeginTime, $adInfo->adApplyEndTime]);
		
		return $infoList;
    }
    public function setServiceIdsAttribute($serviceIds) {
        $this->attributes['serviceIds'] = trim(implode($serviceIds, ','), ',');
    }
}
